// pages/youXuan/tabBar/shopCart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopList:wx.getStorageSync('yx-shoplist')||[],//公共数据
    activeIdx:2,
    list:[],
    sum:0,
    isAll:true//全选
  },
  getShopCart(){
    //获取购物车存储数据
    let list=wx.getStorageSync('yx-shopcart')||[]
    let shopList=wx.getStorageSync('yx-shoplist')||[]
    list.forEach((i)=>{
      i.isShow=true
    })
    this.setData({
      list,
      shopList
    })
    this.getSum()
  },
  setShopCart(item){
    //操作公共购物车数据
    let list=wx.getStorageSync('yx-shopcart')
    let shoplist=wx.getStorageSync('yx-shoplist')
    if(list&&list.length>0){
      let bol=false,idx
      list.forEach((i,index)=>{
        if(i.id==item.id){
          if(item.num==0){
            idx=index
          }else{
            i.num=item.num
          }
          bol=true
        }
        if((index+1)==list.length){
          if(!bol){
            list.push(item)
          }else{
            if(idx>=0){
              list.splice(idx,1)
            }
          }
        }
      })
    }else{
      list=[item]
    }
    shoplist.forEach((i)=>{
      if(i.id==item.id){
        i.num=item.num
      }
    })
    wx.setStorageSync('yx-shopcart',list) 
    wx.setStorageSync('yx-shoplist',shoplist) 
    this.getShopCart()
  },
  changeSelect(event){
    //切换select
    var index=event.currentTarget.dataset.index
    var list=this.data.list
    list[index].isShow=!list[index].isShow
    this.setData({
      list
    })
    this.getSum()
  },
  changeSelectAll(){
    //全选
    var list=this.data.list
    var isAll=!this.data.isAll
    list.forEach((i)=>{
      i.isShow=isAll
    })
    this.setData({
      list,
      isAll
    })
    this.getSum()
  },
  jianFunc(event){
    //减
    var index=event.currentTarget.dataset.index
    var list=this.data.list
    if(list[index].num>0){
      list[index].num--
    }
    this.setShopCart(list[index])
  },
  addFunc(event){
    //加
    var index=event.currentTarget.dataset.index
    var list=this.data.list
    list[index].num++
    this.setShopCart(list[index])
  },
  getSum(){
    //合计
    var list=this.data.list
    let sum=0
    if(list.length>0){
      list.forEach((i)=>{
        if(i.isShow){
          sum+=Number(i.money)*Number(i.num)
        }
      })
    }
    this.setData({
      sum
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getShopCart()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})